#include "LED_Control.h"
#include "USART_SendString.h"
#include "USART_RecvString.h"

uint8_t recv_str[MAX_STR_LEN] = {0}; 		// 静态存储区
uint8_t recv_idx = 0;						// 数组索引

/**
 * @brief  USART1接收中断服务函数
 * @param  无
 * @retval 无
 * @note   即使有FreeRTOS，接收字符依然需要依靠中断触发
 */
void USART1_IRQHandler(void) {
	// 接收中断
	if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){   	// 等待接收寄存器数据发送完毕，即状态更换为SET后退出
		char ch = USART_ReceiveData(USART1);
		recv_str[recv_idx++] = ch;
		
		if(recv_idx >= MAX_STR_LEN - 1){
			recv_str[MAX_STR_LEN - 1] = '\0';
			BaseType_t xHigherPriorityTaskWoken = pdTRUE;
			xQueueSendFromISR(xQueue, recv_str, &xHigherPriorityTaskWoken);
			recv_idx = 0;
		}else if(ch == '\r' ||  ch == '\n'){
			recv_str[recv_idx] = '\0';
			BaseType_t xHigherPriorityTaskWoken = pdTRUE;
			xQueueSendFromISR(xQueue, recv_str, &xHigherPriorityTaskWoken);
			recv_idx = 0;
		}else{
			
		}
		
		USART_ClearITPendingBit(USART1, USART_IT_RXNE);			// 标志位由硬件自动清除
	}
}

/**
 * @brief  配置USART1外设的中断源, 以及初始化NVIC外设
 * @param  无
 * @retval 无
 * @note   
 */
void USART1_NVIC_Init(void){
	// 在USART初始化代码中开启中断和空闲中断
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);  // 接收中断
	
	NVIC_EnableIRQ(USART1_IRQn);                    // 使能USART1全局中断
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); // 4位抢占优先级
	NVIC_InitTypeDef NVIC_InitStruct;
    NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 12;  // 抢占优先级
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;          // 子优先级
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStruct);
}

